﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class InstrumentCostImport : BasePage
    {
        public string BillYear
        {
            get
            {
                if (Request.QueryString["billYear"] != null) return Request.QueryString["billYear"].ToString();
                else return "0000";
            }

        }

        public string BillMonth
        {
            get
            {
                if (Request.QueryString["billMonth"] != null) return Request.QueryString["billMonth"].ToString();
                else return "00";
            }

        }

        public string importType
        {
            get
            {
                if (Request.QueryString["importtype"] != null) return Request.QueryString["importtype"].ToString();
                else return "1";
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlBudgetYear.SelectedValue = System.DateTime.Today.Year.ToString("00");
                ddlBudgetMonth.SelectedValue = System.DateTime.Today.Month.ToString("00");
            }

        }
        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string sYear, sMonth;
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            int sucNum = 0;

            if (fileupload.HasFile) {
                string isXls = System.IO.Path.GetExtension(fileupload.FileName).ToString().ToLower();
                if (isXls != ".xls" && isXls != ".xlsx")
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入文件格式必须是Excel');", true);
                    return; 
                }
                //string file = System.IO.Path.GetFileName(fileupload.FileName).ToString();
                string fileName = fileupload.FileName;
                fileupload.PostedFile.SaveAs(Server.MapPath("\\Temp") + "\\" + fileName);
                string filepath = Server.MapPath("\\Temp") + "\\" + fileName;

                //BillBll bll = new BillBll();
                
                //try
                //{
                //    DataTable dt = ExcelImport.ExcelToDT(filepath, "sheet1");

                //    for (int index = 0; index < dt.Rows.Count; index++) {
                //        string Billcompany = dt.Rows[index]["公司"].ToString();
                        
                //        string cInvCode = dt.Rows[index]["存货编号"].ToString().Trim();
                //        string cInvName = dt.Rows[index]["存货名称"].ToString().Trim();
                //        string cInvStd = dt.Rows[index]["规格"].ToString().Trim();
                //        string Unit = dt.Rows[index]["导入单价"].ToString().Trim();
                //        bll.DelInstrumentCost(sYear, sMonth, Billcompany, cInvCode);

                //        using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
                //        {
                //            try
                //            {
                //                BGcompanyInstrumentCostEntity entity = new BGcompanyInstrumentCostEntity();
                //                entity.InstrumentCostID = Guid.NewGuid();
                //                entity.InstrumentCode = cInvCode;
                //                entity.CompanyName = Billcompany;
                //                entity.CostYear = System.Convert.ToInt16(sYear);
                //                entity.CostMonth = System.Convert.ToInt16(sMonth);
                //                if (DataValid.IsNumeric(Unit))
                //                {
                //                    entity.Cost = System.Convert.ToDecimal(Unit);
                //                    entity.CostImport = System.Convert.ToDecimal(Unit);
                //                }

                //                bll.Insert(entity);
                                
                //            }
                //            catch (Exception ex)
                //            {
                //                txtResult.Text += ",导入失败(出错行：" + (index + 2).ToString() + ")，错误提示："+ex.Message+"\r\n";
                //                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + ",导入中断(出错行：" + (index + 2).ToString() + ")')", true);

                //            }
                //            finally
                //            {
                //                trans.Complete();
                //                sucNum++;
                                
                //            }
                //        }
                //    }
                //    txtResult.Text += "\r\n"+"数据导入完成。共成功导入" + Convert.ToSingle(sucNum)+"条数据。";
                //    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入完成!');", true);
                //}
                //catch(Exception ex) {
                //    txtResult.Text += ",导入失败，错误提示：" + ex.Message + "\r\n";
                //    ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + "');", true);
                //    return;
                //}
                if (importType == "1")
                { importInitCost(filepath); }
                else { importAdjustCost(sYear,sMonth,filepath); }

            }
        }

        private void importInitCost(string filepath)
        {

            int sucNum = 0;

            BillBll bll = new BillBll();

            try
            {
                DataTable dt = ExcelImport.ExcelToDT(filepath, "sheet1");

                for (int index = 0; index < dt.Rows.Count; index++)
                {
                    string Billcompany = dt.Rows[index]["公司"].ToString();

                    string cInvCode = dt.Rows[index]["存货编号"].ToString().Trim();
                    string Unit = dt.Rows[index]["导入单价"].ToString().Trim();
                    bll.DelInstrumentCost(Billcompany, cInvCode);

                    using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
                    {
                        try
                        {
                            BGcompanyInstrumentCostEntity entity = new BGcompanyInstrumentCostEntity();
                            entity.InstrumentCostID = Guid.NewGuid();
                            entity.InstrumentCode = cInvCode;
                            entity.CompanyName = Billcompany;
                            entity.updatetime = System.DateTime.Today;
                            entity.Updatedman = base.CurrentUserEntity.UserName;
                            if (DataValid.IsNumeric(Unit))
                            {
                                entity.CostImport = System.Convert.ToDecimal(Unit);
                            }

                            bll.Insert(entity);

                        }
                        catch (Exception ex)
                        {
                            txtResult.Text += ",导入失败(出错行：" + (index + 2).ToString() + ")，错误提示：" + ex.Message + "\r\n";
                            ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + ",导入中断(出错行：" + (index + 2).ToString() + ")')", true);

                        }
                        finally
                        {
                            trans.Complete();
                            sucNum++;

                        }
                    }
                }
                txtResult.Text += "\r\n" + "数据导入完成。共成功导入" + Convert.ToSingle(sucNum) + "条数据。";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入完成!');", true);
            }
            catch (Exception ex)
            {
                txtResult.Text += ",导入失败，错误提示：" + ex.Message + "\r\n";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + "');", true);
                return;
            }
            txtResult.Text += "\r\n" + "正在更新标准存货的初始成本数据...";
            string msgRtn = new BillBll().UpdateInstrumentCost(Convert.ToInt16(ddlBudgetYear.SelectedValue),Convert.ToInt16(ddlBudgetMonth.SelectedValue));
            if (msgRtn != "")
            { 
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + msgRtn + "');", true);
                txtResult.Text += "\r\n" + "更新标准存货的初始成本数据是发生错误：" + msgRtn;
            }
            else
            { txtResult.Text += "\r\n" + "已成功更新标准存货的初始成本数据。"; }
        }

        private void importAdjustCost(string sYear, string sMonth, string filepath)
        {

            int sucNum = 0;

            BillBll bll = new BillBll();

            try
            {
                DataTable dt = ExcelImport.ExcelToDT(filepath, "sheet1");

                for (int index = 0; index < dt.Rows.Count; index++)
                {
                    string Billcompany = dt.Rows[index]["公司"].ToString();

                    string cInvCode = dt.Rows[index]["存货编号"].ToString().Trim();
                    string Unit = dt.Rows[index]["调整单价"].ToString().Trim();
                    bll.DelInstrumentCost(sYear, sMonth, Billcompany, cInvCode);

                    using (System.Transactions.TransactionScope trans = new System.Transactions.TransactionScope())
                    {
                        try
                        {
                            BGGroupInstrumentCostEntity entity = new BGGroupInstrumentCostEntity();
                            entity.InstrumentCostID = Guid.NewGuid();
                            entity.InstrumentCode = cInvCode;
                            entity.CostYear = System.Convert.ToInt16(sYear);
                            entity.CostMonth = System.Convert.ToInt16(sMonth);
                            entity.updatetime = System.DateTime.Today;
                            entity.Updatedman = base.CurrentUserEntity.UserName;
                            if (DataValid.IsNumeric(Unit))
                            {
                                entity.CostAdjust = System.Convert.ToDecimal(Unit);
                            }

                            if (entity.CostAdjust != 0 && entity.CostAdjust==null)
                            {
                                bll.Insert(entity);
                                bll.updateInstrumentAdjustCost(cInvCode, sYear, sMonth, entity.CostAdjust, base.CurrentUserEntity.UserName);
                            }

                        }
                        catch (Exception ex)
                        {
                            txtResult.Text += ",导入失败(出错行：" + (index + 2).ToString() + ")，错误提示：" + ex.Message + "\r\n";
                            ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + ",导入中断(出错行：" + (index + 2).ToString() + ")')", true);

                        }
                        finally
                        {
                            trans.Complete();
                            sucNum++;

                        }
                    }
                }
                txtResult.Text += "\r\n" + "数据导入完成。共成功导入" + Convert.ToSingle(sucNum) + "条数据。";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('导入完成!');", true);
            }
            catch (Exception ex)
            {
                txtResult.Text += ",导入失败，错误提示：" + ex.Message + "\r\n";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + ex.Message + "');", true);
                return;
            }
        }

    }
}


